package fun.codedesign.jdk.lang.string;

import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;

public class CharCountDemo {
    public static void main(String[] args) {

        String s = "123213213213啊dad分aab adfladflajf;a ";
        Map<Character, Integer> map = count(s);
        System.out.println(map);


        Set<Entry<Character, Integer>> entrySet = map.entrySet();

        ArrayList<Entry<Character, Integer>> list =
                new ArrayList<Entry<Character, Integer>>(entrySet);
        Collections.sort(list, new ByValue());
        for (Entry<Character, Integer> entry : list) {
            char key = entry.getKey();
            int value = entry.getValue();
            DecimalFormat format = new DecimalFormat("0.##%");
            System.out.println(key + "\t" + value + "\t" + format.format((double) value / s.length()));
        }
    }

    public static Map<Character, Integer> count(String s) {

        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                int count = map.get(c) + 1;
                map.put(c, count);
            } else {
                map.put(c, 1);
            }
        }
        return map;
    }
}

class ByValue implements Comparator<Entry<Character, Integer>> {
    public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
        return o2.getValue() - o1.getValue();
    }
}
